package com.java.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author jl
 * Created on 2020/9/29
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        // 创建2个线程组
        // bossGroup只处理连接请求,真正的业务处理会交给workerGroup完成
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建服务器端启动配置
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup) // 设置2个线程组
                    .channel(NioServerSocketChannel.class) // 服务器端使用NioServerSocketChannel作为通道的实现
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列的连接数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 设置workerGroup的EventLoop的管道处理器
                        @Override
                        protected void initChannel(SocketChannel sc) {
                            sc.pipeline().addLast(new NettyServerHandler());
                        }
                    });

            System.out.println(" server is ready");
            // 启动服务
            ChannelFuture channelFuture = bootstrap.bind(6667).sync();
            // future-listener机制
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("绑定端口6667成功");
                    }
                }
            });
            // 监听异步关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
